package com.acme.bankapp.dal;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Set;

import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.domain.client.Client;
import com.acme.bankapp.domain.client.ClientExistsException;
import com.acme.bankapp.service.BankService;

public class BankDataService {
	private static final String DEFAULT_SAVE_PATH = "bank.ser";

	public static void loadFeedFromFile(Bank bank, String path)
			throws IOException, InvalidFeedFormatException,
			ClientExistsException {
		FileInputStream fis = new FileInputStream(path);
		Set<Client> clients = ClientFeedDAO.getAllClientsFromFeed(fis);
		
		for (Client client : clients) {
			BankService.addClient(bank, client);
		}
	}
	
	public static void saveBankToFile(Bank bank) throws IOException {
		saveBankToFile(bank, DEFAULT_SAVE_PATH);
	}
	
	public static void saveBankToFile(Bank bank, String path) throws IOException {
		FileOutputStream fos = new FileOutputStream(path);
		BankSerializationDAO.saveBank(bank, fos);
	}
	
	public static Bank readBankFromFile(String path) throws ClassNotFoundException, IOException {
		FileInputStream fis = new FileInputStream(path);
		return BankSerializationDAO.readBank(fis);
	}
}
